<template>
  <form-builder
    ref="form"
    :fields="formFields"
    :value="value"
    mode="customer"
    class="bbx-cell-form-builder"
    @update="update"
    :isSampleValid="false"
    :form-cell-count="formCellCount"
    :formEditingMode="formEditingMode"
    @getDeleteFiles="getDeleteFiles"
  >
    <template slot="serialNumber" slot-scope="{ field }">
      <form-item
        :label="field.displayName"
        :validation="validation.serialNumber"
        class="bbx-form-cell-item"
        v-if="validation.serialNumber && initData && !initData.isAutoSerialNumber"
      >
        <form-text
          v-if="
            validation.serialNumber && initData && !initData.isAutoSerialNumber
          "
          :field="field"
          :value="value.serialNumber"
          @update="update"
        />
        <div v-else class="form-item__text">{{$t('customer.edit.serialNumberTip')}}</div>
      </form-item>
      <!-- 纯客服云版本不显示客户标签 -->
      <form-item class="bbx-form-cell-item" :label="$t('customer.components.customerEditForm.customerTag.label')" v-if="isCreate && _isShowCustomerTag">
        <div class="form-item-customer-tag-edit">
          <customer-tag-edit
            :line-height="38"
            @change="onCustoemrTagChangeHandler"
            :show-edit="true"
            :value="value.customerTag"
          />
        </div>
      </form-item>
    </template>
    
    <template slot="name" slot-scope="{field}">
      <form-item class="bbx-form-cell-item" :label="field.displayName" :validation="validation.name">
        <div class="input-and-btn">
          <form-text :field="field" :value="value.name" @update="update" />
          <el-button v-if="SaveCustomer" type="plain-third" @click="isCustomer = true"> 
            {{$t('customer.components.customerEditForm.name.button')}}
          </el-button>
        </div>
      </form-item>
    </template>
    
    <template slot="lmName" slot-scope="{field}">
      <form-item class="bbx-form-cell-item" :label="field.displayName" validation>
        <div class="input-and-btn">
          <form-text :field="field" :value="value.lmName" @update="update" />
          <el-button type="plain-third" @click="copyName"
            >{{$t('customer.components.customerEditForm.lmName.label')}}</el-button
          >
        </div>
      </form-item>
    </template>

    <template
      slot="lmPhone"
      slot-scope="{ field }">
      <form-item class="bbx-form-cell-item" :label="field.displayName" :validation="validation.lmPhone" ref="lmPhone" :form="value">
        <form-phone
          :field="field"
          :value="value.lmPhone"
          :placeholder="field.placeholder || ''"
          @update="update" />
      </form-item>
    </template>

    <template slot="customerAddress" slot-scope="{ field }">
      <form-item class="bbx-form-item" :class="[`bbx-from-item-cell-box-${formCellCount}`]" :label="field.displayName" validation>
        <form-address
          :field="field"
          :value="value.customerAddress"
          @update="update"
          :country-clearable="true"
          @update-address-backup="updateAddressBackup"
          :address-backup="addressBackup"
          :class="addressClass"
        />
      </form-item>
    </template>

    <template slot="manager" slot-scope="{ field }">
      <form-item class="bbx-form-cell-item" :label="field.displayName">
        <form-user
          :field="field"
          :value="value.manager"
          @update="update"
          :see-all-org="seeAllOrg"
          :selectOptions="managerSelectOptions"
          selectFn="all"
        />
      </form-item>
    </template>

    <template slot="tags" slot-scope="{ field }">
      <form-item class="bbx-form-cell-item" :label="field.displayName">
        <customer-tags
          :field="field"
          :value="value.tags"
          @autoAssign="autoAssign"
          @input="update"
        />
      </form-item>
    </template>

    <!-- 选择客户 -->
    <CustomerDialog
      v-if="isCustomer"
      :isClose="isCustomer"
      @CustomerClose="CustomerClose"
    />
  </form-builder>
</template>

<script>
import { triggerConnectorUpdate } from '@src/util/assist';
import * as CustomerApi from "@src/api/CustomerApi.ts";
import * as LinkmanApi from "@src/api/LinkmanApi";

import FormMixin from "@src/component/form/mixin/form";
import TeamMixin from "@src/mixins/teamMixin";

import _ from "lodash";
import platform from "@src/platform";

import CustomerTagEdit from "@src/modules/customer/view/components/CustomerTagEdit/CustomerTagEdit.tsx";
/* enum */
import ComponentNameEnum from "@model/enum/ComponentNameEnum.ts";
import CustomerDialog from "../edit/components/CustomerDialog.vue";
import { chooseExUser } from '@model/config/SelectUserConfig.ts'
/* mixin */
import { VersionControlCustomerMixin } from '@src/mixins/versionControlMixin'

export default {
  name: "customer-edit-form",
  mixins: [TeamMixin, VersionControlCustomerMixin],
  props: {
    isCreate: {
      type: Boolean,
      default: false,
    },
    SaveCustomer:{
      type: Boolean,
      default: false,
    },
    fields: {
      type: Array,
      required: true,
    },
    value: {
      type: Object,
      required: true,
    },
    id: {
      type: String,
      // required: true,
      default: "",
    },
    formCellCount: {
      type: Number,
      default: 1,
    },
  },
  inject: ["initData"],
  data() {
    return {
      validation: this.buildValidation(),
      addressBackup: this.value.customerAddress,
      filterTeams: [],
      isCustomer:false,
      managerSelectOptions: chooseExUser,
      needServerDeleFiles: []
    };
  },
  computed: {
    formFields(){
      let arr = this.fields.map(item=>{
        if(item.fieldName == 'lmPhone'){
          item['onlyAllowReg'] = /^[1-9][0-9]{8}$/;
        }else if(item.fieldName == 'synergies'){
          item['setting'] = {
            ...(item.setting || {}),
            selectOptions:this.managerSelectOptions,
            selectFn:'all',
            max:100
          }
        } else if(item.fieldName === 'name') { // 目前没有配置客户名称输入字数限制的功能 所以先在这里写死
          item['setting'] = {
            ...(item.setting || {}),
            isLimitWord: 1,
            limitWordMax: 200
          }
        }
        return item
      })
      return arr
    },
    /** 是否只显示 自己所在团队 */
    seeAllOrg() {
      return true;
    },
    /** 当前用户的权限 */
    permission() {
      return this.initData.loginUser.authorities;
    },
    // 是否含有客户编辑全部权限
    hasEditCustomerAuth() {
      return this.initData?.loginUser?.authorities?.["CUSTOMER_EDIT"] === 3;
    },
    // 是否过滤团队
    isFilterTag() {
      return (
        this.initData &&
        this.initData.isDivideByTag &&
        !this.hasEditCustomerAuth
      );
    },
    formEditingMode() {
      return this.isCreate ? 'create' : 'edit'
    },
    addressClass() {
      return [this.formCellCount === 1 && 'cell-1-margin-b' ]
    },
  },
  methods: {    
    // 获取客户信息
    CustomerClose(info){
      this.isCustomer = false
      this.$emit("CustomerInfo",info)
    },
    isClose(){
      this.isCustomer = false
    },
    buildValidation() {
      let { isAutoSerialNumber, isCustomerNameDuplicate, isPhoneUnique } =
        this.initData;

      let checkCustomerName = _.debounce(function (
        params,
        resolve,
        changeStatus
      ) {
        changeStatus(true);
        return CustomerApi.unique(params)
          .then((res) => {
            changeStatus(false);
            return resolve(res.error ? res.error : null);
          })
          .catch((err) => console.error(err));
      },
      500);

      let checkCustomerSN = _.debounce(function (
        params,
        resolve,
        changeStatus
      ) {
        changeStatus(true);
        return CustomerApi.unique(params)
          .then((res) => {
            changeStatus(false);
            return resolve(res.error ? res.error : null);
          })
          .catch((err) => console.error(err));
      },
      500);

      let checkLmPhone = _.debounce(function (params, resolve, changeStatus) {
        changeStatus(true);
        return LinkmanApi.checkUnique4Phone(params)
          .then((res) => {
            changeStatus(false);
            return resolve(res.error ? res.error : null);
          })
          .catch((err) => console.error(err));
      }, 500);

      const that = this;

      return Object.freeze({
        serialNumber: isAutoSerialNumber
          ? true
          : function (value, field, changeStatus) {
              let params = {
                id: that.id || (that.initData && that.initData.id) || "",
                fieldName: "serialNumber",
                value,
              };

              return new Promise((resolve, reject) =>
                checkCustomerName(params, resolve, changeStatus)
              );
            },
        name: isCustomerNameDuplicate
          ? true
          : function (value, field, changeStatus) {
              let params = {
                id: that.id || (that.initData && that.initData.id) || "",
                fieldName: "name",
                value,
              };

              return new Promise((resolve, reject) =>
                checkCustomerSN(params, resolve, changeStatus)
              );
            },
        lmPhone: !isPhoneUnique
          ? true
          : function (value, field, changeStatus) {
              // 原先电话必填，现在存在非必填的情况，如果没填电话，此处不做是否存在相同号码的校验，否则接口会返回已存在
              if (!value) return null
              let params = {
                customerId:
                  that.id || (that.initData && that.initData.id) || "",
                phone: value,
              };

              return new Promise((resolve, reject) =>
                checkLmPhone(params, resolve, changeStatus)
              );
            },
      });
    },
    update({ field, newValue, oldValue }) {
      let { fieldName, displayName } = field;
      if (this.$appConfig.debug) {
        console.info(
          `[FormBuilder] ${displayName}(${fieldName}) : ${JSON.stringify(
            newValue
          )}`
        );
      }
      let value = this.value;
      this.$set(value, fieldName, newValue);
      this.$emit("input", value);

      triggerConnectorUpdate(this, field);

    },
    copyName() {
      let value = this.value;
      if (!value.name) return;

      this.$set(value, "lmName", value.name);
      this.$emit("input", value);
    },
    /** 自动匹配客户服务团队 */
    async autoAssign() {
      try {
        let adr = this.value.customerAddress;
        let { province, city, dist } = adr;
        if (!province || !city) return this.$platform.alert(this.$t('customer.components.customerEditForm.autoAssign.alert.title'));

        let result = await CustomerApi.matchTag({ province, city, dist });

        if (result.status == 1) {
          return platform.notification({
            type: "error",
            title: this.$t('customer.components.customerEditForm.autoAssign.notify.title'),
            message: result.message,
          });
        }

        let tags = result.data || [];
        if (tags.length == 0) {
          return this.autoAssignFailNotification();
        }

        this.value.tags = tags.map((item) => ({
          id: item.id,
          tagName: item.tagName,
        }));

        if (this.value.tags.length <= 0) {
          return this.autoAssignFailNotification();
        }

        this.$emit("input", this.value);
      } catch (error) {
        console.error(error);
      }
    },
    autoAssignFailNotification() {
      platform.notification({
        type: "error",
        title: this.$t('customer.components.customerEditForm.autoAssignFailNotification.title'),
        message: this.$t('customer.components.customerEditForm.autoAssignFailNotification.message'),
      });
    },
    updateAddressBackup(ad) {
      this.addressBackup = ad;
    },
    validate() {
      return this.$refs.form.validate(false);
    },
    onCustoemrTagChangeHandler(value) {
      this.$set(this.value, "customerTag", value);
      this.$emit("input", this.value);
    },
    // 删除附件
    getDeleteFiles(files) {
      this.needServerDeleFiles = [...this.needServerDeleFiles, ...files]
    }
  },
  components: {
    "customer-tags": {
      name: "customer-tags",
      mixins: [FormMixin],
      props: {
        field: {
          type: Object,
          default: () => ({}),
        },
        value: {
          type: Array,
          default: () => [],
        },
      },
      render(h) {
        // 当前账号是否存在服务商部门
        const isProviderSign = sessionStorage.getItem('isProviderSign') == 1;
        let userMessage;
        if(!isProviderSign) {
          userMessage = (
            <el-button type="plain-third" onClick={this.autoAssign}>
              {this.$t('common.base.autoDispatch')}
            </el-button>
          )
        }

        return (
          <div class="input-and-btn">
            <biz-team-select value={this.value} onInput={this.input} multiple />
            { userMessage }
          </div>
        );
      },
      methods: {
        autoAssign() {
          this.$emit("autoAssign");
        },
        input(value) {
          this.$emit("input", {
            field: this.field,
            newValue: value,
            oldValue: [],
          });
        },
      },
    },
    [ComponentNameEnum.CustomerTagEdit]: CustomerTagEdit,
    CustomerDialog:CustomerDialog,
  }
};
</script>

<style lang="scss">
.form-item-customer-tag-edit {
  line-height: 30px;
}
.bbx-from-item-cell-box-1 {
  .cell-1-margin-b {
    .country-cls {
      margin-bottom: 16px !important;
    }
  }
}
</style>
